

//? 原型上写
Array.prototype.flatt = function (depth = 1) {
    let res = []
    depth--
    //? 找需要扁平的数组
    for (let item of Array.from(this)) {
        if (Object.prototype.toString.call(item).includes('Array')) {
            //? 根据需要的深度 递归
            if (depth > 0) {
                res = res.concat(item.flatt(depth))
                // res.push(...item.flatt(depth))
            }
            //? 达到指定depth后展开
            else res.push(...item)
        }
        //? 保证所有的都展开了
        else {
            res.push(item)
        }
    }
    return res
}
//? 普通方法
function flat(arr, depth = Infinity) {
    depth--
    let res = []
    arr.forEach((item,index) => {
        if (Array.isArray(item)) {
            if (depth) {
                res.push(...flat(item,depth))
                // res = res.concat(flat(item,depth))
            }
            else {
                res.push(...item)
            }
        }
        else {
            res.push(item)
        }
    })
    return res
}

const arr = [1, [2, 3, [4, 5, [10, 12]]], 1, 2, [6, 7]]
console.log(arr.flatt())
console.log(arr.flatt(2))
console.log(arr.flatt(Infinity))
//? reduce方法实现
const flattenByDepth = (arr, depth = 1) => {
    if (depth === 0) return arr;
    return arr.reduce((acc, cur) => {
        return acc.concat(Array.isArray(cur)? flattenByDepth(cur, depth - 1) : cur);
    }, []);
};

const multiNestedArr = [1, [2, [3, [4]]]];
const flattenedByDepthArr = flattenByDepth(multiNestedArr, 2);

console.log(flattenedByDepthArr);

